# coding:utf8
from smtplib import SMTP_SSL
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import yaml
from common.Logger import logger, path
from common.result import Result
from get_path import get_pathdir


class Mail:
    """
        powered by Mr Will
        at 2018-12-22
        用来获取配置并发送邮件
    """

    def __init__(self):
        # 读取配置文件
        f = open(file=path + "lib/conf.yml", mode='r', encoding="utf-8")
        self.mail_info = yaml.safe_load(stream=f)['mail']
        f.close()

        # 发件人
        self.mail_info['from'] = self.mail_info['username']
        # smtp服务器域名，截取域名，然后拼上smtp.
        self.mail_info['hostname'] = 'smtp.' + self.mail_info['username'] \
            [self.mail_info['username'].rfind('@') + 1:self.mail_info['username'].__len__()]

        logger.info(self.mail_info)

    def send(self, text):
        # 这里使用SMTP_SSL就是默认使用465端口，如果发送失败，可以使用587
        smtp = SMTP_SSL(self.mail_info['hostname'], port=465)
        smtp.set_debuglevel(0)

        ''' SMTP 'ehlo' command.
        Hostname to send for this command defaults to the FQDN of the local
        host.
        '''
        smtp.ehlo(self.mail_info['hostname'])
        # 登录
        smtp.login(self.mail_info['username'], self.mail_info['password'])

        # 普通HTML邮件
        # msg = MIMEText(text, 'html', self.mail_info['mail_encoding'])

        # 支持附件的邮件
        msg = MIMEMultipart()
        msg.attach(MIMEText(text, 'html', self.mail_info['mail_encoding']))
        msg['Subject'] = Header(self.mail_info['mail_subject'], self.mail_info['mail_encoding'])
        # msg['from'] = self.mail_info['from']
        # 添加自定义昵称
        h = Header(self.mail_info['mailnick'], 'utf-8')
        h.append('<' + self.mail_info['from'] + '>', 'ascii')
        msg["from"] = h

        # logger.debug(self.mail_info)
        # logger.debug(text)
        msg['to'] = ','.join(self.mail_info['to'])
        msg['cc'] = ','.join(self.mail_info['cc'])
        receive = self.mail_info['to']
        receive += self.mail_info['cc']

        # 添加附件
        for i in range(len(self.mail_info['filepaths'])):
            att1 = MIMEText(open(self.mail_info['filepaths'][i], 'rb').read(), 'base64', 'utf-8')
            att1['Content-Type'] = 'application/octet-stream'
            # att1['Content-Disposition'] = 'attachment; filename= "'+self.mail_info['filenames'][i]+'"'
            att1.add_header('Content-Disposition', 'attachment', filename=('gbk', '', self.mail_info['filenames'][i]))

            msg.attach(att1)

        try:
            smtp.sendmail(self.mail_info['from'], receive, msg.as_string())
            smtp.quit()
            logger.info('邮件发送成功')
        except Exception as e:
            logger.error('邮件发送失败：')
            logger.exception(e)


if __name__ == '__main__':
    mail = Mail()
    # # 处理相对路径为绝对路径
    mail.mail_info['filepaths'] = [get_pathdir + '\\lib\\cases\\result-电商项目用例.xlsx']
    mail.mail_info['filenames'] = ['WEB电商项目用例.xlsx']

    res = Result()
    result = res.get_res('\\lib/cases\\result-电商项目用例.xlsx')
    print(result)
    runtype = result.get("runtype")
    title = result.get("title")
    starttime = result.get("starttime")
    endtime = result.get("endtime")
    casecount = result.get("casecount")
    passrate = result.get("passrate")
    status = result.get("status")
    with open(get_pathdir + r'\lib\module1.html', mode='r', encoding='utf8') as f:
        text = f.read()
        text = text.replace("status", f"{status}")
        text = text.replace("passrate", f"{passrate}")
        text = text.replace("casecount", f"{casecount}")
        text = text.replace("endtime", f"{endtime}")
        text = text.replace("starttime", f"{starttime}")
        text = text.replace("title", f"{title}")
        text = text.replace("runtype", f"{runtype}")
        print(text)
        raw_index = ""
        groups = res.get_groups('\\lib\\cases\\result-电商项目用例.xlsx')[1:]
        print(groups)
        for group in groups:
            index_text = '<tr><td width="100" height="28" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">分组信息</td><td width="80" height="28" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">用例总数</td><td width="80" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">通过数</td><td width="80" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">状态</td></tr>'
            group_info = group[0]
            case_num = group[1]
            pass_num = group[2]
            status = group[3]
            index_text = index_text.replace("分组信息", f"{group_info}")
            index_text = index_text.replace("用例总数", f"{case_num}")
            index_text = index_text.replace("通过数", f"{pass_num}")
            index_text = index_text.replace("状态", f"{status}")
            raw_index += index_text
        text=text.replace("mailbody",raw_index)


    mail.send(text)
